﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Photocopy.Business;
using Photocopy.Model;
using System.IO;
using System.Reflection;
using System.Globalization;

namespace Photocopy
{
    public partial class NewProduct : System.Web.UI.Page
    {
        private DataTable GetOption()
        {
            DataTable dtOptions = null;
            if(ViewState["OptionID"]!=null)
            {
                int OptionID = Convert.ToInt32((ViewState["OptionID"]));
                OptionID++;
                ViewState["OptionID"] = OptionID;
            }
            else
            {
                ViewState["OptionID"] = 1;
            }
            if(ViewState["OptionTable"] == null)
            {
                dtOptions = new DataTable("OptionTable");
                dtOptions.Columns.Add(new DataColumn("OptionID",typeof(int)));
                dtOptions.Columns.Add(new DataColumn("MainOptionID",typeof(string)));
                dtOptions.Columns.Add(new DataColumn("MainOptionName", typeof(string)));
                dtOptions.Columns.Add(new DataColumn("OptionName",typeof(string)));
                dtOptions.Columns.Add(new DataColumn("Options",typeof(string)));
                ViewState["OptionTable"] = dtOptions;
            }
            else
            {
                dtOptions = (DataTable)ViewState["OptionTable"];
            }
            Dictionary<string, string> titleoption = (Dictionary<string, string>)ViewState["MainOption"];
            DataRow dr = dtOptions.NewRow();
            dr["OptionID"] = Convert.ToInt32(ViewState["OptionID"]);
            dr["MainOptionID"] = titleoption[ddlistTitleMainOption.SelectedItem.ToString()];
            dr["MainOptionName"] = ddlistTitleMainOption.SelectedItem.ToString();
            dr["OptionName"] = txtOptionName.Text.Trim();
            dr["Options"] = txtOption.Text.Trim();
            dtOptions.Rows.Add(dr);
            ViewState["OptionTable"] = dtOptions;
            return dtOptions;
        }
        private DataTable GetDiscount()
        {
            DataTable dtDiscounts = null;
            if (ViewState["DiscountTable"] == null)
            {
                dtDiscounts = new DataTable("DiscountTable");
                dtDiscounts.Columns.Add(new DataColumn("Quantity", typeof(int)));
                dtDiscounts.Columns.Add(new DataColumn("Value", typeof(string)));
                dtDiscounts.Columns.Add(new DataColumn("UserGroup", typeof(string)));
                ViewState["DiscountTable"] = dtDiscounts;
            }
            else
            {
                dtDiscounts = (DataTable)ViewState["DiscountTable"];
            }
            DataRow dr = dtDiscounts.NewRow();
            dr["Quantity"] = txtQuantityDiscount.Text.Trim();
            dr["Value"] = txtValueDiscount.Text.Trim() + " " + dropValueDiscount.SelectedItem.ToString();
            dr["UserGroup"] = dropUserGroup.SelectedItem.ToString();
            dtDiscounts.Rows.Add(dr);
            ViewState["DiscountTable"] = dtDiscounts;
            return dtDiscounts;
        }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //ProductData dp = new ProductData();
                //RptImage.DataSource = dp.GetImage("C01");
                //RptImage.DataBind();
            }
        }

        protected void btnAddMainOption_Click(object sender, EventArgs e)
        {
            if (ViewState["MainOptionID"] != null)
            {
                int TitleOptionID = Convert.ToInt32((ViewState["MainOptionID"]));
                TitleOptionID++;
                ViewState["MainOptionID"] = TitleOptionID;
            }
            else
            {
                ViewState["MainOptionID"] = 1;
            }
            ddlistTitleMainOption.Items.Add(new ListItem(txtMainOption.Text));
            if (ViewState["MainOption"] != null)
            {
                Dictionary<string, string> titleoptionid = (Dictionary<string, string>)ViewState["MainOption"];
                titleoptionid.Add(txtMainOption.Text, txtProNameId.Text + "_" + Convert.ToString((ViewState["MainOptionID"])));
                ViewState["MainOption"] = titleoptionid;                
                txtMainOption.Text = string.Empty;
            }
            else
            {
                Dictionary<string, string> titleoptionid = new Dictionary<string, string>();
                titleoptionid.Add(txtMainOption.Text, txtProNameId.Text + "_" + Convert.ToString((ViewState["MainOptionID"])));
                ViewState["MainOption"] = titleoptionid;
                txtMainOption.Text = string.Empty;
            }
        }

        protected void btnAddOption_Click(object sender, EventArgs e)
        {
            DataTable dtOptions = new DataTable();
            lblOptionMessage.Visible = false;
            if (CheckProNameID(txtProNameId.Text) == true)
            {
                dtOptions = GetOption();
                if (ViewState["OptionTable"] != null)
                {
                    dtOptions = (DataTable)ViewState["OptionTable"];

                    RptOptions.DataSource = dtOptions;
                    RptOptions.DataBind();
                    RptOptions.Visible = true;
                }
                else
                {
                    RptOptions.DataSource = null;
                    RptOptions.DataBind();
                    RptOptions.Visible = false;
                }

                txtOption.Text = string.Empty;
                txtOptionName.Text = string.Empty;
            }
            else
            {
                lblOptionMessage.Visible = true;
                lblOptionMessage.Text = "Hãy nhập mã sản phẩm trước khi thêm chức năng.";
            }
        }
       
        protected void btnAddDiscount_Click(object sender, EventArgs e)
        {
            DataTable dtDiscounts = new DataTable();
            dtDiscounts = GetDiscount();
            if (ViewState["DiscountTable"] != null)
            {
                dtDiscounts = (DataTable)ViewState["DiscountTable"];

                RptDiscount.DataSource = dtDiscounts;
                RptDiscount.DataBind();
                RptDiscount.Visible = true;
            }
            else
            {
                RptDiscount.DataSource = null;
                RptDiscount.DataBind();
                RptDiscount.Visible = false;
            }
            txtQuantityDiscount.Text = string.Empty;
            txtValueDiscount.Text = string.Empty;
        }

        protected void btnReset_Click(object sender, EventArgs e)
        {
            ResetAll();
        }

        protected void RptDiscount_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            RepeaterItem item = e.Item;
            if(e.CommandName == "Delete")
            {
                DataTable dtDiscounts = (DataTable)ViewState["DiscountTable"];
                dtDiscounts.Rows[item.ItemIndex].Delete();
                dtDiscounts.AcceptChanges();

                ViewState["DiscountTable"] = dtDiscounts;
                //rebind the Repeater with the updated DataTable
                RptDiscount.DataSource = dtDiscounts;
                RptDiscount.DataBind();
            }
        }

        protected void RptOptions_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            RepeaterItem item = e.Item;
            if (e.CommandName == "Delete")
            {
                DataTable dtOptions = (DataTable)ViewState["OptionTable"];
                dtOptions.Rows[item.ItemIndex].Delete();
                dtOptions.AcceptChanges();

                ViewState["OptionTable"] = dtOptions;
                //rebind the Repeater with the updated DataTable
                RptOptions.DataSource = dtOptions;
                RptOptions.DataBind();
            }
            if(e.CommandName == "Edit")
            {
                ((Label)e.Item.FindControl("lbOptionName")).Visible = false;
                ((Label)e.Item.FindControl("lbOptions")).Visible = false;
                ((TextBox)e.Item.FindControl("txtOptionNameUpdate")).Visible = true;
                ((TextBox)e.Item.FindControl("txtOptionUpdate")).Visible = true;
                ((ImageButton)e.Item.FindControl("imgBtnEdit")).Visible = false;
                ((ImageButton)e.Item.FindControl("imgBtnDelete")).Visible = false;
                ((Button)e.Item.FindControl("btnUpdate")).Visible = true;
            }
            if (e.CommandName == "Update")
            {
                DataTable dtOptions = (DataTable)ViewState["OptionTable"];
                DataRow dr = dtOptions.Rows[item.ItemIndex];
                dr["OptionName"] = ((TextBox)e.Item.FindControl("txtOptionNameUpdate")).Text.Trim();
                dr["Options"] = ((TextBox)e.Item.FindControl("txtOptionUpdate")).Text.Trim();
                ((Label)e.Item.FindControl("lbOptionName")).Text = ((TextBox)e.Item.FindControl("txtOptionNameUpdate")).Text.Trim();
                ((Label)e.Item.FindControl("lbOptions")).Text = ((TextBox)e.Item.FindControl("txtOptionUpdate")).Text.Trim();
                ((Label)e.Item.FindControl("lbOptionName")).Visible = true;
                ((Label)e.Item.FindControl("lbOptions")).Visible = true;
                ((TextBox)e.Item.FindControl("txtOptionNameUpdate")).Visible = false;
                ((TextBox)e.Item.FindControl("txtOptionUpdate")).Visible = false;
                ((ImageButton)e.Item.FindControl("imgBtnEdit")).Visible = true;
                ((ImageButton)e.Item.FindControl("imgBtnDelete")).Visible = true;
                ((Button)e.Item.FindControl("btnUpdate")).Visible = false;
                ViewState["OptionTable"] = dtOptions;
                //rebind the Repeater with the updated DataTable
                RptOptions.DataSource = dtOptions;
                RptOptions.DataBind();
            }
        }

        protected void btnInsertProduct_Click(object sender, EventArgs e)
        {
            ProductData dp = new ProductData();
            string Masanxuat;
            Masanxuat = ChangeCompanyID(dropCompany.SelectedItem.ToString());
            ProductRP product = new ProductRP();
            product.MaSanPham = txtProNameId.Text;
            product.MaSanXuat = Masanxuat;
            product.TenSanPham = txtProName.Text;
            product.DonGia = Int32.Parse(txtPrice.Text);
            product.SoLuong = Int32.Parse(txtQuantity.Text);
            product.NgayNhapHang = Convert.ToDateTime(txtDateImport.Text);
            dp.InsertProduct(product);
            int sanphamid = dp.GetSanphamID(txtProNameId.Text, Masanxuat, txtProName.Text);            
            MainOptionList to = new MainOptionList();            
            foreach(ListItem li in ddlistTitleMainOption.Items)
            {
                to.SanPhamID = sanphamid;
                to.MainOptionName = li.Text.ToString();
                dp.InsertMainOption(to);
            }
            OptionDetail od = new OptionDetail();
            DataTable dt = (DataTable)ViewState["OptionTable"];
            for (int i = 0; i < dt.Rows.Count;i++ )
            {
                DataRow dr = dt.Rows[i];             
                int mainoptionid = dp.GetMainOptionID(sanphamid, Convert.ToString(dr["MainOptionName"]));
                od.MainOptionID = mainoptionid;
                od.OptionName = Convert.ToString(dr["OptionName"]);
                od.OptionDescription = Convert.ToString(dr["Options"]);
                dp.InsertOption(od);
            }

            string message = "Thêm sản phẩm thành công";
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("<script type = 'text/javascript'>");
            sb.Append("window.onload=function(){");
            sb.Append("alert('");
            sb.Append(message);
            sb.Append("')};");
            sb.Append("</script>");
            ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
            ResetAll();

        }
        private string ChangeCompanyID(string Nhasanxuat)
        {
            string companyid;
            switch(Nhasanxuat)
            {
                case "Fuji Xerox":
                    companyid = "SX01";
                    break;
                case "Canon":
                    companyid = "SX02";
                    break;
                case "Toshiba":
                    companyid = "SX03";
                    break;
                case "Ricoh":
                    companyid = "SX04";
                    break;
                case "Sharp":
                    companyid = "SX05";
                    break;
                case "Kyocera":
                    companyid = "SX06";
                    break;
                case "Konica Minolta":
                    companyid = "SX07";
                    break;
                default:
                    companyid=null;
                    break;
            }

            return companyid;
        }
        private void ResetAll()
        {
            txtProName.Text = string.Empty;
            txtProNameId.Text = string.Empty;
            dropCompany.SelectedIndex = 0;
            txtPrice.Text = string.Empty;
            txtQuantity.Text = string.Empty;
            txtDateImport.Text = string.Empty;
            txtMainOption.Text = string.Empty;
            ddlistTitleMainOption.Items.Clear();
            txtOptionName.Text = string.Empty;
            txtOption.Text = string.Empty;
            ViewState["OptionTable"] = null;
            RptOptions.DataSource = null;
            RptOptions.DataBind();
            txtPackageWeight.Text = string.Empty;
            cbFreeShipping.Checked = false;
            txtShippingFreight.Text = string.Empty;
            txtPackageLength.Text = string.Empty;
            txtPackageHeight.Text = string.Empty;
            txtPackageWidth.Text = string.Empty;
            txtQuantityDiscount.Text = string.Empty;
            txtValueDiscount.Text = string.Empty;
            dropUserGroup.SelectedIndex = 0;
            ViewState["DiscountTable"] = null;
            RptDiscount.DataSource = null;
            RptDiscount.DataBind();
        }
        private bool CheckProNameID(string Masanpham)
        {
            if(Masanpham != null && Masanpham != "")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

  
        
        //protected bool CheckFileType(string fileName)
        //{

        //    string ext = Path.GetExtension(fileName);
        //    switch (ext.ToLower())
        //    {
        //        case ".gif":
        //            return true;
        //        case ".png":
        //            return true;
        //        case ".jpg":
        //            return true;
        //        case ".jpeg":
        //            return true;
        //        default:
        //            return false;
        //    }
        //}

        //protected void btnSubmit_Click(object sender, EventArgs e)
        //{

        //    if (Page.IsValid && UploadImg.HasFile && CheckFileType(UploadImg.FileName))
        //    {
        //        string filename = Path.GetFileName(UploadImg.PostedFile.FileName);
        //        string chuoi = filename.Substring(0, filename.IndexOf('.'));
        //        filename = filename.Replace(chuoi, "ảnh");
        //        UploadImg.SaveAs(Server.MapPath("Images/" + DateTime.Now.ToString("ddMMyy_hhmm_") + filename));
        //        ProductData pd = new ProductData();
        //        pd.InsertImage("C01", DateTime.Now.ToString("ddMMyy_hhmm_") + filename, "Images/" + DateTime.Now.ToString("ddMMyy_hhmm_") + filename);
        //        RptImage.DataSource = pd.GetImage("C01");
        //        RptImage.DataBind();

        //    }
        //}
        //protected void RptImage_ItemCommand(object source, RepeaterCommandEventArgs e)
        //{

        //    //if (e.CommandName == "RemoveImage")
        //    //{
        //    //    ProductData pd = new ProductData();
        //    //    Label lbImage = (Label)e.Item.FindControl("lbImageName");
        //    //    pd.DeleteImage("C01", lbImage.Text);
        //    //    RptImage.DataSource = pd.GetImage("C01");
        //    //    RptImage.DataBind();
        //    //}
        //}

        //public static T Clone<T>(this T controlToClone)
        //where T : Control
        //{
        //    PropertyInfo[] controlProperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

        //    T instance = Activator.CreateInstance<T>();

        //    foreach (PropertyInfo propInfo in controlProperties)
        //    {
        //        if (propInfo.CanWrite)
        //        {
        //            if (propInfo.Name != "WindowTarget")
        //                propInfo.SetValue(instance, propInfo.GetValue(controlToClone, null), null);
        //        }
        //    }

        //    return instance;
        //}
    }
}